package proxy

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"math/big"
	"os"
	"time"
)

func newCertificate() (certDER, keyPEM []byte, err error) {
	// 生成 ECC 私钥
	priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to generate private key: %v", err)
	}

	// 创建证书模板
	template := x509.Certificate{
		SerialNumber:          new(big.Int).SetBytes([]byte{0x54, 0xc7, 0xe1, 0xd0, 0xd1, 0x85, 0x20, 0x93, 0xcd, 0xb5, 0xca, 0xcc, 0x41, 0x80, 0xed, 0x58}), // 默认序列号
		Subject:               pkix.Name{CommonName: "PPH"},                                                                                                  // 默认"PPH"作为CN
		NotBefore:             time.Now().AddDate(-1, 0, 0),
		NotAfter:              time.Now().Add(90 * 365 * 24 * time.Hour), // 证书有效期1年
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		ExtKeyUsage:           nil, // CA证书没有必要指定服务端身份验证等
		BasicConstraintsValid: true,
		IsCA:                  true, // 设置为CA证书
	}

	// 生成证书并签名
	certDER, err = x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to create certificate: %v", err)
	}

	// 将私钥编码为 PEM 格式
	keyPEM, err = x509.MarshalECPrivateKey(priv)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to marshal private key: %v", err)
	}

	return certDER, keyPEM, nil
}

func saveCertificate(certDER, keyPEM []byte) error {
	// 保存证书为 CER 格式
	certFile, err := os.Create("PPH.cer")
	if err != nil {
		return fmt.Errorf("failed to create cert file: %v", err)
	}
	defer certFile.Close()

	// 写入 DER 编码证书
	_, err = certFile.Write(certDER)
	if err != nil {
		return fmt.Errorf("failed to write cert file: %v", err)
	}

	// 保存证书为 PEM 格式
	certFile, err = os.Create("PPH.crt")
	if err != nil {
		return fmt.Errorf("failed to create cert file: %v", err)
	}
	defer certFile.Close()

	// 写入 PEM 编码的证书
	err = pem.Encode(certFile, &pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certDER,
	})
	if err != nil {
		return fmt.Errorf("failed to write cert file: %v", err)
	}

	// 保存私钥为 PEM 格式
	keyFile, err := os.Create("key.pem")
	if err != nil {
		return fmt.Errorf("failed to create key file: %v", err)
	}
	defer keyFile.Close()

	// 写入 PEM 格式的私钥
	_, err = keyFile.Write(keyPEM)
	if err != nil {
		return fmt.Errorf("failed to write key file: %v", err)
	}

	// 保存私钥为 PEM 格式
	rsaKeyFile, err := os.Create("PPH.key")
	if err != nil {
		return fmt.Errorf("failed to create key file: %v", err)
	}
	defer rsaKeyFile.Close()
	// 写入 PEM 编码的私钥
	err = pem.Encode(rsaKeyFile, &pem.Block{
		Type:  "RSA PRIVATE KEY", // 确保私钥类型为 RSA PRIVATE KEY
		Bytes: keyPEM,
	})
	if err != nil {
		return fmt.Errorf("failed to write key file: %v", err)
	}
	return nil
}

func createCertificate() {
	// 生成证书和私钥
	certDER, keyPEM, err := newCertificate()
	if err != nil {
		fmt.Println("Error generating certificate:", err)
		return
	}

	// 保存证书和私钥
	err = saveCertificate(certDER, keyPEM)
	if err != nil {
		fmt.Println("Error saving certificate:", err)
		return
	}

	fmt.Println("证书和私钥已保存为 cert.cer 和 key.pem")
}
